<!--
 * @Author: 九璃怀特 1599130621@qq.com
 * @Date: 2023-10-17 10:38:39
 * @LastEditors: 九璃怀特 1599130621@qq.com
 * @LastEditTime: 2023-10-17 16:02:28
 * @FilePath: \any-project\src\views\WebGPU\pages\demo1.vue
 * @Description: 
 -->
<template>
  <div class="demo1" ref="demo1">
    <canvas style="width: 100%;" height="100%" ref="gpuCanvas"></canvas>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";

const gpuCanvas = ref<HTMLCanvasElement>();
const demo1 = ref<HTMLDivElement>()

onMounted(() => {
  const canvas = gpuCanvas.value!;
  canvas.width = demo1.value!.clientWidth*devicePixelRatio 
  canvas.height = demo1.value!.clientHeight*devicePixelRatio 
  const gl = canvas.getContext("webgl")!;
  // 顶点着色器代码
  const vsSource = `
  attribute vec4 coordinates;
  void main(void) {
    gl_Position = coordinates;
  }
`;

  // 片段着色器代码
  const fsSource = `
  void main(void) {
    gl_FragColor = vec4(1.0, 1.0, 1.0, 1); // 红色线条
  }
`;

  // 编译顶点着色器
  const vs = gl.createShader(gl.VERTEX_SHADER)!;
  gl.shaderSource(vs, vsSource);
  gl.compileShader(vs);

  if (!gl.getShaderParameter(vs, gl.COMPILE_STATUS)) {
    console.error(
      "An error occurred compiling the shaders: " + gl.getShaderInfoLog(vs)
    );
    gl.deleteShader(vs);
  }

  // 编译片段着色器
  const fs = gl.createShader(gl.FRAGMENT_SHADER)!;
  gl.shaderSource(fs, fsSource);
  gl.compileShader(fs);

  if (!gl.getShaderParameter(fs, gl.COMPILE_STATUS)) {
    console.error(
      "An error occurred compiling the shaders: " + gl.getShaderInfoLog(fs)
    );
    gl.deleteShader(fs);
  }

  // 创建着色器程序
  const shaderProgram = gl.createProgram()!;
  gl.attachShader(shaderProgram, vs);
  gl.attachShader(shaderProgram, fs);
  gl.linkProgram(shaderProgram);
  gl.useProgram(shaderProgram);
  gl.lineWidth(5.5)
  // 设置顶点坐标
  const vertices = new Float32Array([0, -1, 0, 1,0.5, -1, 0.5, 1]);
  const lines = 4
  let mockArr:number[] = []
  for(let i = 0;i<=lines;i++){
    const num = (i/lines*2)-1
    mockArr.push(num,-1,num,1)
    mockArr.push(-1,num,1,num)
  }
  const vertices2 = new Float32Array(mockArr);
  gl.lineWidth(3.0)
  // 创建缓冲区
  const buffer = gl.createBuffer();
  gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  gl.bufferData(gl.ARRAY_BUFFER, vertices2, gl.STATIC_DRAW);

  // 获取坐标属性的位置
  const position = gl.getAttribLocation(shaderProgram, "coordinates");
  gl.vertexAttribPointer(position, 2, gl.FLOAT, false, 0, 0);
  gl.enableVertexAttribArray(position);

  // 清空画布
  gl.clearColor(0.0, 0.0, 0.0, 1.0);
  gl.clear(gl.COLOR_BUFFER_BIT);

  // 绘制线条
  gl.drawArrays(gl.LINES, 0, lines*4);
});
</script>

<style lang="less" scoped>
.demo1 {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
}
</style>
